<template>
  <div id="add-chart">
    <a-row :gutter="24">
      <a-col :span="12">
        <a-card title="智能分析">
          <a-form
            :model="formState"
            name="add_chart"
            v-bind="formItemLayout"
            @finishFailed="onFinishFailed"
            @finish="onFinish"
          >
            <a-form-item
              label="分析目标"
              name="goal"
              :rules="[{ required: true, message: '请输入分析目标' }]"
            >
              <a-textarea
                v-model:value="formState.goal"
                placeholder="请输入你的分析目标，例如：分析网站用户的增长情况"
              ></a-textarea>
            </a-form-item>
            <a-form-item label="图表名称" name="name">
              <a-input
                v-model:value="formState.name"
                placeholder="请输入你的图表名称"
              ></a-input>
            </a-form-item>
            <a-form-item name="chartType" label="图表类型" has-feedback>
              <a-select
                v-model:value="formState.chartType"
                placeholder="请选择图表类型"
                :options="[
                  { value: '折线图', label: '折线图' },
                  { value: '柱状图', label: '柱状图' },
                  { value: '堆叠图', label: '堆叠图' },
                  { value: '饼图', label: '饼图' },
                  { value: '雷达图', label: '雷达图' },
                ]"
              >
              </a-select>
            </a-form-item>

            <a-form-item name="file" label="原始数据">
              <a-upload
                v-model:fileList="fileList"
                :before-upload="beforeUpload"
              >
                <a-button>
                  <template #icon>
                    <UploadOutlined />
                  </template>
                  上传 CSV 文件
                </a-button>
              </a-upload>
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 12, offset: 6 }">
              <a-button
                type="primary"
                html-type="submit"
                :loading="submitting"
                :disabled="submitting"
                >提交
              </a-button>
              <a-button style="margin-left: 10px" html-type="reset"
                >重置
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>
      <a-col :span="12">
        <a-card title=" 分析结论">
          <div v-if="!chart?.analyze">请先在左侧提交</div>
          <div v-else>
            {{ chart?.analyze }}
          </div>
          <a-spin v-if="submitting" />
        </a-card>
        <a-divider></a-divider>
        <a-card title="可视化图表">
          <div v-if="!chart?.chartCode">请先在左侧提交</div>
          <a-spin v-if="submitting" />
          <div id="myEChartsBar" style="width: 100%; height: 400px"></div>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watchEffect } from "vue";
import { useRouter } from "vue-router";
import {
  ChartControllerService,
  GenChartVo,
  TestControllerService,
  UserControllerService,
} from "../../../generated";

import { UploadOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import { AnyObject } from "ant-design-vue/es/_util/type";
import * as echarts from "echarts";

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};

const fileList = ref<AnyObject>([]);

const formState = reactive<Record<string, any>>({
  name: "",
});

const chart = ref<GenChartVo>();

const drawOption = async () => {
  const myEChart = await echarts.init(document.getElementById("myEChartsBar"));
  myEChart.clear();
  let option = chart.value?.chartCode;
  if (option) {
    await myEChart.setOption(JSON.parse(option));
  }
  // 根据页面大小自动响应图表大小
  window.addEventListener("resize", function () {
    myEChart.resize();
  });
};

let submitting = ref<boolean>(false);

/**
 * 提交
 * @param values
 */
const onFinish = async (values: any) => {
  let res = await UserControllerService.getLoginUserUsingGet();
  if (!res.data) {
    message.error(res.message);
    return;
  }
  if (submitting.value) {
    return;
  }
  submitting.value = true;
  values = formState;
  try {
    const res = await ChartControllerService.genChartByAiUsingPost(
      values.goal,
      values.name,
      fileList.value[0].originFileObj,
      values.chartType
    );
    if (res.code === 200) {
      message.success("分析成功");
      chart.value = res.data;
      drawOption();
    } else {
      message.error("分析失败");
    }
  } catch (e: any) {
    message.error("分析失败" + e.message);
  }
  submitting.value = false;
};

const beforeUpload = (file: File) => {
  return new Promise((resolve) => {
    fileList.value.push(file);
    const isJpgOrPng =
      file.type ===
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    if (!isJpgOrPng) {
      message.error("只能上传xlsx格式!");
      return false;
    } else {
      return resolve(false);
    }
  });
};

const onFinishFailed = (errorInfo: any) => {
  console.log("Failed:", errorInfo);
};

const loadData = async () => {
  let res = await TestControllerService.testListUsingGet();
};

/**
 * 监听 searchParams 变量，改变时触发页面的重新加载
 */
watchEffect(() => {
  loadData();
});

/**
 * 页面加载时请求数据
 */
onMounted(() => {
  loadData();
});

const router = useRouter();
</script>

<style scoped></style>
